package com.gvfish.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Service;

import com.google.appengine.api.datastore.Text;
import com.gvfish.entity.Article;
@Service
public class FetchManager {
	public String get(URL url){
		StringBuilder sb = new StringBuilder();
		        try {
		            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(),"gb2312"));
		            String line;

		            while ((line = reader.readLine()) != null) {
		               sb.append(line);
		            }
		            reader.close();

		        } catch (MalformedURLException e) {
		            // ...
		        } catch (IOException e) {
		            // ...
		        }
		        return sb.toString();
	}
	public String get(String str){
		URL url = null;
		try {
			url = new URL(str);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		return get(url);
	}
	public String getWiki(String word){
		String encodedWord=null;
		try {
			encodedWord=java.net.URLEncoder.encode(word,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String url = "http://www.hudong.com/wiki/"+encodedWord;
		return get(url);
	}
	public Article  getCnFish(String url){
		Article  article = new Article();
		article.setFrom("Internet");
		article.setAuthor("admin");
		String content = get(url);
		String title = "<title>(.*?)_观赏鱼之家</title>";
		String neirong = "<span id=\"ctl00_ContentPlaceHolder1_Label6\">(.*?)</span>";
		Pattern p = Pattern.compile(title);
		Matcher m = p.matcher(content);
		if(m.find()){
			System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			System.out.println(m.group(1));
			article.setTitle(m.group(1));
			article.setKeyWords(article.getTitle());
			System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		}
		p = Pattern.compile(neirong);
		m=p.matcher(content);
		if(m.find()){
			System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
			System.out.println(m.group(1));
			article.getDetails().setText(new Text(m.group(1)));
			System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
		}
		return article;
	}
}
